package org.yoyo.classroom.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yoyo.classroom.domain.po.LostFound;
import org.yoyo.classroom.request.LostFoundRequest;
import org.yoyo.classroom.result.Result;
import org.yoyo.classroom.service.LostFoundService;
import org.yoyo.classroom.utils.JwtTokenUtil;

import java.util.List;

/**
 * 失物招领控制器
 */
@RestController
@RequestMapping("/lost-found")
public class LostFoundController {

    @Autowired
    private LostFoundService lostFoundService;

    /**
     * 根据ID查询失物招领信息
     * @param id 失物招领ID
     * @return 包含失物招领对象的结果
     */
    @GetMapping("/{id}")
    public Result<LostFound> getLostFoundById(@PathVariable Long id) {
        LostFound lostFound = lostFoundService.getLostFoundById(id);
        if (lostFound != null) {
            return Result.success(lostFound);
        } else {
            return Result.error("Lost found item not found");
        }
    }

    /**
     * 条件查询失物招领信息
     */
    @GetMapping("/")
    public Result<List<LostFound>> getLostFounds(
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) String sort
    ) {
        List<LostFound> lostFounds = lostFoundService.getLostFoundsByCondition(type, status, search, sort);
        return Result.success(lostFounds);
    }

    /**
     * 插入失物招领信息
     * @param lostFound 失物招领对象
     * @return 包含影响行数的结果
     */
    @PostMapping("/")
    public Result<Integer> addLostFound(@RequestBody LostFound lostFound) {
        int affectedRows = lostFoundService.addLostFound(lostFound);
        return Result.success(affectedRows);
    }

    /**
     * 更新失物招领信息
     * @param lostFound 失物招领对象
     * @return 包含影响行数的结果
     */
    @PutMapping("/")
    public Result<Integer> updateLostFound(@RequestBody LostFound lostFound) {
        int affectedRows = lostFoundService.updateLostFound(lostFound);
        return Result.success(affectedRows);
    }

    /**
     * 删除失物招领信息（逻辑删除）
     * @param id 失物招领ID
     * @return 包含影响行数的结果
     */
    @DeleteMapping("/{id}")
    public Result<Integer> deleteLostFound(@PathVariable Long id) {
        int affectedRows = lostFoundService.deleteLostFound(id);
        return Result.success(affectedRows);
    }

    /**
     * 发布失物招领信息
     */
    @PostMapping
    public Result<LostFound> publish(@RequestBody LostFoundRequest request,
                                     @RequestHeader(value = "Authorization", required = false) String authorizationHeader
                                     ) {
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        Long userId;
        // 检查并解析 token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            // 2. 验证 Token
            String username = jwtTokenUtil.getUsernameFromToken(token);

            userId=jwtTokenUtil.getUserIdFromToken(token);

        } else {

            return Result.error("请先登录！！！");
        }
        try {
            // 转换请求参数为实体对象
            LostFound lostFound = new LostFound();
            // 转换类型：lost->1, found->0
            lostFound.setType(request.getType().equals("lost") ? "1" : "0");
            lostFound.setTitle(request.getTitle());
            lostFound.setDescription(request.getDescription());
            lostFound.setRoomName(request.getLocation());
            lostFound.setCreateTime(request.getDate());
            lostFound.setImageUrl(request.getImageUrl());
            lostFound.setContact(request.getContact());

            // TODO: 从当前登录用户中获取用户信息
            lostFound.setUserId(userId);
            // lostFound.setUserName(getCurrentUserName());

            // 保存信息
            int result = lostFoundService.addLostFound(lostFound);

            return Result.success(lostFound);
        } catch (Exception e) {
            return Result.error("发布失败：" + e.getMessage());
        }
    }
}
